import React, {Component} from 'react';
import {createPage, base, high} from 'nc-lightapp-front';
import requestApi from './requestApi';
import {buttonClick, initTemplate, afterEvent, beforeEvent, refreshButtonClick} from './events';

import {
    ProfileStyle,
    ProfileHead,
    ProfileBody,
    BodyLeft,
    BodyRight,
    HeadCenterCustom,
    EmptyArea,
    ButtonGroup
} from 'ssccommon/components/profile';
import BusinessUnitTreeRef from 'uapbd/refer/org/BusinessUnitTreeRef';
import {SyncTree} from 'ssccommon/components/tree';
import {EditTable} from 'ssccommon/components/table';
import pubMessage from 'ssccommon/utils/pubMessage'
import {setForm} from 'ssccommon/utils/setComponentUsed';
import {Form} from 'ssccommon/components/bill';


import './index.less';

class TreeTable extends Component {
    constructor(props) {
        super(props);
        setForm(props, 'rule_code');
        this.metaparam = {};
        this.state = {
            treeSearchDisabled: false,
            refreshStatus: 'browse'
        };
        this.pubMessage = new pubMessage(props);

        buttonClick.saveBtnEventConfig.click = buttonClick.saveBtnEventConfig.click.bind(this);
        buttonClick.treeSelectEvent = buttonClick.treeSelectEvent.bind(this);
        buttonClick.btnEventMapping['Add'].click = buttonClick.btnEventMapping['Add'].click.bind(this);
        buttonClick.btnEventMapping['Edit'].click = buttonClick.btnEventMapping['Edit'].click.bind(this);
        buttonClick.btnEventMapping['Cancel'].click = buttonClick.btnEventMapping['Cancel'].click.bind(this);
        buttonClick.btnEventMapping['Delete'].click = buttonClick.btnEventMapping['Delete'].click.bind(this);
        buttonClick.tableBtnEventMapping['AddLine'].click = buttonClick.tableBtnEventMapping['AddLine'].click.bind(this);
        buttonClick.tableBtnEventMapping['DelLine'].click = buttonClick.tableBtnEventMapping['DelLine'].click.bind(this);
        initTemplate.call(this, props);
    }

    openFormula() {
        this.metaparam = this.queryMetaParam() || {};
    }

    queryMetaParam() {
        let metaparam = {};
        if (this.props.syncTree.getSyncTreeValue('tree1') == undefined || this.props.syncTree.getSelectNode('tree1') == null) {
            return metaparam;
        }
        let srcbilltype = this.props.syncTree.getSelectNode('tree1').refcode;
        if (this.props.syncTree.getSelectNode('tree1').pid != '~') {
            srcbilltype = this.props.syncTree.getSyncTreeValue('tree1', this.props.syncTree.getSelectNode('tree1').pid).refcode;
        }

        // 查询
        requestApi.queryMetaParam({
            data: {
                src_billtype: srcbilltype
            },
            success: (res) => {
                metaparam = {
                    pk_billtype: srcbilltype,
                    bizmodelStyle: res.data.moduleid,
                    classid: res.data.beanid
                };
                this.metaparam = metaparam;
                this.setState({ showFormula: true });
            }
        });
    }

    componentWillMount() {
        window.onbeforeunload = () => {
            // debugger;
            let status = this.props.editTable.getStatus('reimrule');
            if (status == 'edit' || status == 'add') {
                return '';
            }
        };
    }

    async componentDidMount() {
        // 获取左侧树
        // let treeData = await new Promise((resolve) => {
        //     requestApi.getTreeData({
        //         data: {},
        //         success(data) {
        //             resolve(data);
        //         }
        //     });
        // });
        // if (treeData.data && treeData.data[0] && treeData.data[0][0]) {
        //     let orginfo = treeData.data[0] && treeData.data[0][0];
        //     this.setState({
        //         pk_org: {
        //             refpk: orginfo[0],
        //             refcode: orginfo[1],
        //             refname: orginfo[2]
        //         }
        //     });
        // }
    }

    onBusinessUnitTreeRefChange(v) {
        if (!v || !v.refpk) return;
        const { props } = this
        const { syncTree } = this.props;
        const { setSyncTreeData } = syncTree;

        this.setState({ pk_org: v });
        // 获取左侧树
        requestApi.getTreeData({
            data: { pk_org: v.refpk },
            success(treeData) {
                // 左树数据打平
                let treenode = ((treeData.data && treeData.data[1]) || []).map((item) => {
                    item.pid = null;
                    item.refname = item.refname || item.name;
                    return item;
                });
                
                let newTree = syncTree.createTreeData(treenode); //创建树 组件需要的数据结构
                setSyncTreeData('tree1', newTree);

                if (treenode && treenode.length === 0) {
                    // this.props.button.setButtonsVisible(['Add', 'Edit', 'Save', 'Cancel', 'Delete', 'Refresh', 'AddLine', 'DelLine'], false);
                    props.form.EmptyAllFormValue('rule_code');
                    let resultData = {
                        rows: []
                    };
                    props.editTable.setTableData('rule_data', resultData);
                    props.syncTree.cancelSelectedNode('tree1');
                    props.syncTree.updataDataSource('tree1', () => []);
                    return;
                }

                //请求分摊规则详情数据
                let reqData = {
                    pagecode: window.presetVar.pagecode,
                    pk: treenode[0].refpk || treenode[0].refcode,
                    pk_org: v.refpk
                };
                requestApi.getTableData({
                    data: reqData,
                    success: (tableData) => {
                        // 选中左树选中项
                        syncTree.setNodeSelected('tree1', treenode[0].refpk);
        
                        buttonClick.setMetaDataFromTreeNode(tableData, props);
                    }
                });
            }
        });
    }

    render() {
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let { createForm } = this.props.form;
        return (
            <ProfileStyle layout='treeTable' {...this.props} id='reimrulerforgroup'>
                {/*页面头*/}
                <ProfileHead
                    // "201101BXBJ-0001": "报销标准设置-集团"
                    title={multiLang && multiLang.get('201103FTGZ-0003')}
                    refreshButtonEvent={refreshButtonClick.bind(this)}
                    status={this.state.refreshStatus}
                >
                    <HeadCenterCustom>
                        <div style={{ width: '204px' }}>
                            <BusinessUnitTreeRef
                                value={this.state.pk_org || {}}
                                disabled={this.state.orgdisabled}
                                onChange={this.onBusinessUnitTreeRefChange.bind(this)}
                                queryCondition={() => {
                                    return {
                                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.BusinessUnitTreeRefBuilder',
                                        appcode: this.props.getSearchParam('c')
                                    };
                                }}
                            />
                        </div>
                    </HeadCenterCustom>

                    <ButtonGroup
                        area='rule_code'
                        buttonLimit='4'
                        buttonEvent={{
                            Save: buttonClick.saveBtnEventConfig,
                            ...buttonClick.btnEventMapping
                        }}
                    />
                </ProfileHead>
                {/*页面体*/}
                <ProfileBody>
                    <BodyLeft>
                        <SyncTree
                            areaId='tree1'
                            disabledSearch={this.state.treeSearchDisabled}
                            selectedForInit={false}
                            onSelectEve={buttonClick.treeSelectEvent.bind(this)}
                        />
                    </BodyLeft>
                    <BodyRight>
                        <div className='form-wrapper' style={{ margin: '1rem 0' }}>
                            {createForm('rule_code', {
                                //编辑后事件
                                onAfterEvent: afterEvent.bind(this)
                            })}
                        </div>

                        <EditTable
                            areaId='rule_data'
                            showIndex={this.state.isShowIndex}
                            showCheck={this.state.isEdit}
                            onAfterEvent={afterEvent.bind(this)}
                            onBeforeEvent={beforeEvent.bind(this)}
                            selectedChange={(props, moduleId, newVal, oldVal) => {
                                if (newVal > 0) {
                                    props.button.setButtonDisabled(['DeleteS'], false);
                                } else if (newVal == 0) {
                                    props.button.setButtonDisabled(['DeleteS'], true);
                                }
                            }}
                        >
                            <ButtonGroup
                                area='rule_data'
                                className='table-btn-edit'
                                buttonEvent={buttonClick.tableBtnEventMapping}
                            />
                        </EditTable>
                    </BodyRight>
                </ProfileBody>
            </ProfileStyle>
        );
    }
}

TreeTable = createPage({
    mutiLangCode: '2011'
})(TreeTable);

export default TreeTable;
